<template>
  <el-container class='elheight'>
    <el-aside class='appTree'>
      <app-tree v-bind:tree-data="treeData" v-on:appTreeClick="treeClickHandle"></app-tree>
    </el-aside>
    <el-main>
      <el-container>
        <el-header class="dzy-main-header">
          <div class="btn-group-el">
            <btn-group :currentSelectedData="currentSelectedData" @btnClickCallback="btnClickCallback"></btn-group>
          </div>
          <div class="dzy-custom-search-box">
            <div>行政区名称：
              <el-input placeholder="请输入行政区名称" v-model="queryData.name" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>行政区编号：
              <el-input placeholder="请输入行政区编号" v-model="queryData.code" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>行政区层级：
              <el-select v-model="queryData.levelCode" clearable placeholder="请选择">
                <el-option v-for="(item,index) in regionOption" :key="index" :label="item.name" :value="item.code"></el-option>
              </el-select>
            </div>
            <div>
              <el-button @click="searchHandleClick" type="primary" icon="el-icon-search">查询</el-button>
            </div>
          </div>
        </el-header>
        <el-main>
          <app-table :page-data="pageData"
            :table-columns="tableColumns"
            v-on:currentChange="handleCurrentChange"
            v-on:handleCheckedRows="handleCheckedRows" />
          <el-dialog
            :title="dialogTitle"
            :visible.sync="dialogFormVisible"
            :before-close="cancel"
            :close-on-click-modal="false">
            <el-form :model="formData" :disabled="showOnly" label-width="120px" size="mini">
              <el-form-item label="上级区域">
                <div class="block">
                  <el-cascader
                    placeholder="请选择"
                    :options="treeData"
                    :props="deptProps"
                    filterable
                    clearable
                    change-on-select
                    :show-all-levels="false"
                    v-model="formData.deptIdArr">
                  </el-cascader>
                </div>
              </el-form-item>
              <el-form-item label="名称">
                <el-input v-model="formData.name" placeholder="请输入行政区名称"></el-input>
              </el-form-item>
              <el-form-item label="行政区编码">
                <el-input v-model="formData.code" placeholder="请输入行政区编码"></el-input>
              </el-form-item>
            </el-form>
            <div v-if="!showOnly" slot="footer" class="dialog-footer">
              <el-button @click="cancel">取 消</el-button>
              <el-button type="primary" @click="save">提 交</el-button>
            </div>
          </el-dialog>
        </el-main>
      </el-container>
    </el-main>
  </el-container>
</template>

<script>
import AppTree from '@/components/common/AppTree'
import BtnGroup from '@/components/BtnGroup'
import AppTable from '@/components/AppTable'
import {getAllRegion} from '@/utils/region'
import {getUserRegionTree} from '@/utils/LocalDataUtil'
import {getDictDataOption} from '@/utils/getDictDataOption'
import {findRegion, createRegion, updateRegion, deleteRegion, getRegionTree, getRegion} from '@/http/AppApi'
export default {
  data () {
    return {
      tableData: [],
      treeData: [],
      pageData: {},
      queryData: {},
      formData: {},
      currentSelectedData: [],
      showOnly: false,
      dialogTitle: '',
      dialogFormVisible: false,
      tableColumns: [
        { label: '行政区名称', prop: 'name' },
        { label: '区域层级', prop: 'levelCode', formatter: this.levelFormatter },
        { label: '行政区编号', prop: 'code' }
      ],
      deptProps: {
        label: 'name',
        value: 'id'
      },
      regionOption: []
    }
  },
  components: {
    BtnGroup,
    AppTable,
    AppTree
  },
  mounted () {
    this.getTableData()
    this.getLocalTreeData()
    this.regionOption = getDictDataOption('层级')
  },
  methods: {
    levelFormatter (row, column) {
      let centerLevelOption = getDictDataOption('层级')
      let resGenterLevel = ''
      for (let i = 0; i < centerLevelOption.length; i++) {
        if (centerLevelOption[i].code === row.levelCode) {
          resGenterLevel = centerLevelOption[i].name
          break
        }
      }
      return resGenterLevel
    },
    save () {
      this.dialogFormVisible = false
      if (this.formData) {
        if (!this.beforeSubmit()) {
          return
        }
        if (this.formData.deptIdArr && this.formData.deptIdArr.length > 0) {
          let len = this.formData.deptIdArr.length - 1
          this.formData.parentId = this.formData.deptIdArr[len]
        }
        if (this.formData.id) {
          updateRegion(this.formData).then(resp => {
            if (resp.code && resp.code === '200') {
              this.queryData.offset = 0
              this.getTableData()
              this.getTreeData()
              this.$message({
                showClose: true,
                message: '修改成功',
                type: 'success'
              })
            } else {
              this.$message({
                type: 'info',
                message: resp.message
              })
            }
          })
        } else {
          createRegion(this.formData).then(resp => {
            if (resp.code && resp.code === '200') {
              this.queryData.offset = 0
              this.getTableData()
              this.getTreeData()
              this.$message({
                showClose: true,
                message: '新增成功',
                type: 'success'
              })
            } else {
              this.$message({
                type: 'info',
                message: resp.message
              })
            }
          })
        }
      }
    },
    del (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          rows.forEach(row => {
            deleteRegion(row).then(resp => {
              if (resp.code && resp.code === '200') {
                this.getTableData()
                this.$message({
                  showClose: true,
                  message: '删除成功',
                  type: 'success'
                })
              } else {
                this.$message({
                  type: 'info',
                  message: resp.message
                })
              }
            })
          })
        })
      }
    },
    cancel () {
      this.dialogFormVisible = false
      this.formData = {}
    },
    getTableData () {
      let param = this.queryData
      findRegion(param).then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          if (data) {
            this.pageData = data
            if (this.pageData.items && this.pageData.items instanceof Array) {
              this.tableData = this.pageData.items
            }
          }
        }
      })
    },
    getTreeData () {
      getRegionTree().then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          if (data && data instanceof Array) {
            console.log(data)
            this.treeData = data
          }
        }
      })
    },
    getLocalTreeData () {
      // getRegionTree().then(resp => {
      //   if (resp.code && resp.code === '200') {
      //     let data = resp.data
      //     if (data && data instanceof Array) {
      //       this.regionTreeData = data
      //     }
      //   }
      // })
      let data = getUserRegionTree()
      if (data && data instanceof Array) {
        console.log(data)
        this.treeData = data
      }
    },
    beforeSubmit () {
      return true
    },
    handleCurrentChange (val) {
      this.queryData.offset = (val - 1) * 10
      this.getTableData()
    },
    btnClickCallback (callbackData) {
      if (callbackData.btnType === 'delete') {
        this.dialogFormVisible = false
        let rows = callbackData.rows
        this.del(rows)
      } else {
        if (callbackData.btnType === 'post') {
          if (this.formData.deptIdArr && this.formData.deptIdArr.length > 0) {
            let arr = this.formData.deptIdArr
            this.formData = {}
            this.$set(this.formData, 'deptIdArr', arr)
          } else {
            this.formData = {}
          }
        } else {
          let obj = JSON.stringify(callbackData.rows[0])
          this.formData = JSON.parse(obj)
          if (this.formData.parentId) {
            let deptData = {}
            deptData.id = this.formData.parentId
            deptData.items = this.treeData
            let deptIdArr = getAllRegion(deptData)
            this.$set(this.formData, 'deptIdArr', deptIdArr)
          }
        }
        this.showOnly = callbackData.sohwOnly
        this.dialogTitle = callbackData.dialogTitle
        this.dialogFormVisible = true
      }
    },
    handleCheckedRows (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        let m = this
        getRegion(rows[0].id).then(resp => {
          if (resp.code && resp.code === '200') {
            m.currentSelectedData = [resp.data]
            m.formData = resp.data
          }
        })
      } else {
        this.currentSelectedData = []
        this.formData = {}
      }
    },
    treeClickHandle (data) {
      this.queryData = {}
      this.queryData.likeId = data.id
      let deptData = {}
      deptData.id = data.id
      deptData.items = this.treeData
      let deptIdArr = getAllRegion(deptData)
      this.$set(this.formData, 'deptIdArr', deptIdArr)
      this.getTableData()
    },
    searchHandleClick () {
      this.queryData.offset = 0
      this.getTableData()
    }
  },
  computed: {},
  watch: {}
}
</script>
<style>
</style>
